package com.zhinong.controller.user;


import com.zhinong.constant.JwtClaimsConstant;
import com.zhinong.dto.UserLoginDTO;
import com.zhinong.entity.User;
import com.zhinong.properties.JwtProperties;
import com.zhinong.result.Result;
import com.zhinong.service.UserService;
import com.zhinong.utils.JwtUtil;
import com.zhinong.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user/user")
@Api(tags = "C端用户登录相关接口")
public class UserController {


    @Autowired
    private UserService userService;


    @Autowired
    private JwtProperties jwtProperties;


    @PostMapping("/login")
    @ApiOperation("微信用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录:{}",userLoginDTO.getCode());
        //微信用户登录
        User user = userService.wxLogin(userLoginDTO);

        //生成JWT

        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .name(user.getName())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }
}
